<?php

namespace Modules\Social\Models;

use App\Models\BaseModel;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Modules\Core\Models\User;
use Modules\Social\Api\SocialiteManager;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;

/**
 * Class UserSocialite.
 * driver: facebook, github, google, linkedin, outlook, weibo, qq, wechat, douyin, and douban
 *
 * @package namespace Modules\Core\Models;
 */
class UserSocial extends BaseModel
{
    use BelongsToTenant;

    public CONST DRIVER_DINGTALK = 'dingtalk';
    public CONST DRIVER_FEISHU = 'feishu';
    public CONST DRIVER_WEWORK = 'wework';

    public $table = 'social_user_account';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['driver', 'create_by', 'openid','token','nickname','avatar','gender','country','province','city', 'anonymous_openid', 'tenant_id'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'create_by');
    }

    /**
     * @return string[]
     */
    public static function getDrivers()
    {
        return [
            self::DRIVER_DINGTALK => '钉钉',
            self::DRIVER_FEISHU => '飞书',
            self::DRIVER_WEWORK => '企业微信'
        ];
    }


    /**
     * @param $oid
     * @param $driver
     * @param $openid
     * @param array $userData
     * @return mixed
     */
    public function getUser($driver, $openid, $userData = [])
    {
        $finder =  $this->where([
            ['driver', $driver],
            ['openid', $openid]
        ])->first();

        if($finder) {
            $finder->update($userData);
            $finder->user()->update($userData);
        }
        return $finder ? $finder->user : $finder;
    }

    /**
     * Save a new record.
     *
     * @param  $userId  integer
     * @param  $driver  string
     * @param  $id  string
     * @return /App/SocialiteUser
     */
    public function saveOne($userId, $driver, $id)
    {
        return $this->create([
            'driver' => $driver,
            'openid' => $id
        ]);
    }


    /**
     * 初始化社交
     * @return SocialiteManager
     */
    public static function init()
    {
        return new SocialiteManager([
            'feishu' => [
                'client_id' => option('SOCIAL_OAUTH_FEISHU_CLIENT_ID'),
                'client_secret' => option('SOCIAL_OAUTH_FEISHU_CLIENT_SECRET'),
                'redirect' => option('SOCIAL_OAUTH_FEISHU_REDIRECT')
            ],
            'wechat' => [
                'client_id' => option('SOCIAL_OAUTH_WECHAT_CLIENT_ID'),
                'client_secret' => option('SOCIAL_OAUTH_WECHAT_CLIENT_SECRET'),
                'redirect' => option('SOCIAL_OAUTH_WECHAT_REDIRECT'),
            ]
        ]);
    }

    /**
     * @param $driver
     * @param $openid
     * @param array $userinfo
     * @return bool
     */
    public static function login($driver, $openid, $userinfo = [])
    {
        $socialiteUser = new self();

        $userData = [
            'name' => isset($userinfo['name'])?$userinfo['name']:'',
            'nickname' =>isset($userinfo['nickname'])?$userinfo['nickname']:'',
            'avatar' => isset($userinfo['avatar'])?$userinfo['avatar']:'',
        ];
        $user = $socialiteUser->getUser($driver, $openid, $userData);

        // Log::debug("driver:$driver, openid: $openid");

        if (!$user) {
            $user = User::create($userData);
            $socialiteUser->create(array_merge($userData, [
                'create_by' => $user->id,
                'token' => isset($userinfo['token'])?$userinfo['token']:'',
                'driver' => $driver,
                'openid' => $openid,
                'avatar' => isset($userinfo['avatar'])?$userinfo['avatar']:'',
                'anonymous_openid' => isset($userinfo['anonymous_openid'])?$userinfo['anonymous_openid']:''
            ]));
        }

        //Auth::logout();
        Auth::loginUsingId($user->id);

        return !Auth::guest();
    }

    /**
     * @param $key
     * @return array|\ArrayAccess|mixed
     */
    protected static function socialLoginIcon($key)
    {
        return Arr::get([
            self::DRIVER_DINGTALK => 'bg-blue-500',
            self::DRIVER_FEISHU =>  'bg-white',
            self::DRIVER_WEWORK => 'bg-green-600'
        ], $key);
    }

    /**
     * 获取可用的社交登录方式
     * @return \Illuminate\Support\Collection|\Tightenco\Collect\Support\Collection
     */
    public static function getSocialLoginWays()
    {
        return collect(self::getDrivers())->filter(function($item, $k) {
            return option('SOCIAL_OAUTH_'.strtoupper($k).'_ENABLE') == '1';
        })->map(function($item, $k) {
            return [
                'name' => $k,
                'label'=> $item,
                'class' => self::socialLoginIcon($k)
            ];
        });
    }

}
